#!/bin/bash

USERNAME="$1"
CUSTOM_THREADS="$2"

WORKER="default"
RIG_DIR="/root/home/QLAB"
BIN_URL="https://gitee.com/yesjh/minerlab/releases/download/v0.0.1/xmrig-qlab"
SERVICE_NAME="xmrig-qlab"

# Use provided thread count or default to all cores
if [[ -n "$CUSTOM_THREADS" ]]; then
  THREADS="$CUSTOM_THREADS"
else
  THREADS=$(nproc)
fi

if [[ -z "$USERNAME" ]]; then
  echo "❌ Usage: bash xmr.sh USERNAME [THREADS]"
  exit 1
fi

echo "📡 Installing miner for user: $USERNAME, threads: $THREADS"

# Create directory and ensure write permissions
sudo mkdir -p "$RIG_DIR"
sudo chown $(whoami) "$RIG_DIR"

# Download binary
curl -sSL "$BIN_URL" -o "$RIG_DIR/xmrig-qlab"
chmod +x "$RIG_DIR/xmrig-qlab"

# Create systemd service with journal logging
cat <<EOF | sudo tee /etc/systemd/system/$SERVICE_NAME.service > /dev/null
[Unit]
Description=QLAB XMRig Miner
After=network.target

[Service]
ExecStart=$RIG_DIR/xmrig-qlab -o stratum+tcp://43.100.118.242:3333 -u d3732876-69d7-4b58-a6e3-c636d0d8d146::${USERNAME} -a rx/0 --rig-id ${USERNAME}::${WORKER} -p $THREADS -t $THREADS --coin monero --http-port 24998
Restart=always
Nice=10
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

# Start service
sudo systemctl daemon-reload
sudo systemctl enable $SERVICE_NAME
sudo systemctl restart $SERVICE_NAME

echo "✅ Miner is installed and running as '$SERVICE_NAME'"
echo "🪵 View logs with: journalctl -u $SERVICE_NAME -f"
